const log4js = require('log4js');
 log4js.configure({
    appenders: {fileout: { type: "file", filename: "./logs/user.log" },consoleout: { type: "console" }},
    categories: {default: { appenders: ["fileout","consoleout"], level: "info" }}
})
const log = log4js.getLogger("user");
log.level = "info"; // default level is OFF - which means no logs at all.
const db = require("../common/mysql");

const save = async (data) =>{
    return new Promise((resolve, reject) => {
        log.info("save: ",data);
        const {pid, ref, address, note, username, mobile, password, state, create_time, update_time}=data;
        const sql = `INSERT INTO ng68.app_user ( pid, ref, address,state, create_time, update_time) VALUES (${pid}, '${ref}', '${address}',0,now(), now());`;
        db.query(sql, (error, results) => {
            if(error){
                // 创建失败
                log.error(`save error: ${address} ${error.sqlMessage} \n ${sql}`);
                reject(error);
            } else {
                // 创建成功
                log.info(`save successfully ${address}`)
                resolve(results[0]);
            }
        })
    })
}

const update =async (data) => {
    return new Promise((resolve, reject) => {
        const {id,pid, ref, address, note, state, create_time, update_time}=data;
        let sql = `update app_user set  
        ref=${ref},
        update_time=now()
        where id=${id}
        `
        log.debug("update: ",sql);
        db.query(sql, (error, results) => {
            if (error) {
                reject(error);
            } else {
                resolve(results);
            }
        })
    })
}


const active =async (address) => {
    return new Promise((resolve, reject) => {
        let sql = `update app_user set  
        state=1,
        update_time=now()
        where address='${address}'
        `
        log.info("update: ",sql);
        db.query(sql, (error, results) => {
            if (error) {
                reject(error);
            } else {
                resolve(results);
            }
        })
    })
}


const list = async () =>{
    const sql = "SELECT * FROM app_user";
    const result =  db.query(sql);
    return result;
}

const getByAddress =async (address) =>{
    return new Promise((resolve, reject) => {
        const sql = `SELECT * FROM app_user WHERE address = '${address}'`;
        log.info("getByAddress: ",sql);
        db.query(sql, (error, results) => {
            if (error) {
                log.error(`error: ${address} ${error.sqlMessage} \n ${sql}`);
                reject(error);
            } else {
                log.debug("getByAddress results: ",results);
                resolve(results[0]);
            }
        })
    })
}



module.exports = {
    save,
    update,
    active,
    list,
    getByAddress,

}